package controllers

import (
	"adminapi/conf"
	"adminapi/libs"
	"adminapi/models"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"strconv"
	"strings"
	"time"
)

type KeywordController struct {
	BaseController
}

func (self *KeywordController) Index() {
	self.Data["pageTitle"] = "API文档"
	self.Data["ts"] = time.Now()
	self.TplName = "keyword/index.html"
}

//前台list
func (self *KeywordController) List() {

	self.Data["pageTitle"] = "KeyWord文档"
	self.Data["ts"] = time.Now()
	//self.ajaxList("成功", MSG_OK, 1, "")
	self.TplName = "keyword/list.html"
}

//前台list
func (self *KeywordController) Jisuan() {

	sum := 0
	for a := 0; a < 10000; a++ {
		for c := 0; c < 5000; c++ {
			sum = sum + c
		}
	}
	connection := conf.GetConnection()
	// close DB
	defer connection.Close()
	db := connection.NewSession()
	//result,err := db.Query("select * from pp_key_word where id = 79879")
	result,err := db.Query("SELECT  * FROM pp_key_word  GROUP BY cn")
	if err != nil {
		fmt.Println(err)
		return
	}
	self.ajaxList("成功", MSG_OK, 1, result)
}

//前台list
func (self *KeywordController) AdminList() {
	self.Data["pageTitle"] = "KeyWord文档"
	self.Data["ts"] = time.Now()
	self.display("keyword/admin_list")
}
//前台list
func (self *KeywordController) LogList() {
	self.Data["pageTitle"] = "KeyWord修改日志"
	self.Data["ts"] = time.Now()
	self.display("keyword/log_list")
}

func (self *KeywordController) Listall() {
	self.Data["pageTitle"] = "KeyWord文档"
	self.Data["ts"] = time.Now()
	//self.ajaxList("成功", MSG_OK, 1, "")
	self.TplName = "keyword/listall.html"
}

func (self *KeywordController) Table() {
	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}
	envName := strings.TrimSpace(self.GetString("envName"))
	cn := strings.TrimSpace(self.GetString("apiName"))

	self.pageSize = limit
	//查询条件
	filters := make([]interface{}, 0)
	//filters = append(filters, "status", 1)
	if envName != "" {
		//filters = append(filters, "env_name__icontains", envName)
	}

	if cn != ""{
		filters = append(filters, "cn__icontains", cn)
	}
	result, count := models.KeyWordGetList(page, self.pageSize, filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["Id"] = v.Id
		row["Key_name"] = v.Key_name
		row["Cn"] = v.Cn
		row["En"] = v.En
		row["Th"] = v.Th
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}
func (self *KeywordController) TableAll() {
	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}
	self.pageSize = limit

	//查询条件
	filters := make([]interface{}, 0)

	result,count := models.KeyWordGetList(page, self.pageSize, filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["ken_name"] = v.Key_name
		row["cn"] = v.Cn
		row["en"] = v.En
		row["th"] = v.Th
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}



//新增接口实例
func (self *KeywordController) Add() {
	self.Data["pageTitle"] = "词库添加"
	//资源
	self.display()
}

func (self *KeywordController) Edit() {
	self.Data["pageTitle"] = "编辑API"

	id, _ := self.GetInt("id", 0)
	Api, err := models.GetById(id)
	if err != nil {
		self.Ctx.WriteString("数据不存在")
		return
	}
	self.Data["info"] = Api
	self.display()
}

//存储资源
func (self *KeywordController) AjaxSave() {
	Api_id, _ := self.GetInt("id")
	if Api_id == 0 {
		Api := new(models.KeyWord)

		Api.Key_name = strings.TrimSpace(self.GetString("key_name"))
		Api.Cn = strings.TrimSpace(self.GetString("cn"))
		Api.En = strings.TrimSpace(self.GetString("en"))
		Api.Th = strings.TrimSpace(self.GetString("th"))

		// 检查登录名是否已经存在
		_, err := models.GetByName(Api.Key_name)
		if err == nil {
			self.ajaxMsg("资源名已经存在", MSG_ERR)
		}

		if _, err := models.Add(Api); err != nil {
			self.ajaxMsg(err.Error(), MSG_ERR)
		}
		self.ajaxMsg("", MSG_OK)
	}
	ApiUpdate, _ := models.GetById(Api_id)
	// 修改
	ApiUpdate.Key_name = strings.TrimSpace(self.GetString("key_name"))
	ApiUpdate.Cn = strings.TrimSpace(self.GetString("cn"))
	ApiUpdate.En = strings.TrimSpace(self.GetString("en"))
	ApiUpdate.Th = strings.TrimSpace(self.GetString("th"))

	if err := ApiUpdate.Update(); err != nil {
		self.ajaxMsg(err.Error(), MSG_ERR)
	}
	self.ajaxMsg("", MSG_OK)
}


func (self *KeywordController) BuildJs() {
	result,count := models.ListALl()

	list_cn := make([]map[string]interface{}, len(result))
	fmt.Print(count)

	list := []int{1, 2, 3, 4, 5, 6, 7}
	res := libs.Implode(list, ",")
	fmt.Println(res)
	fmt.Println(libs.CurrentPath())

	//list_en := make([]map[string]interface{}, len(result))
	//list_th := make([]map[string]interface{}, len(result))
	var str_cn,str_en,str_th,_str_cn string
	str_cn = "export default {"
	str_en = "export default {"
	str_th = "export default {"
	_str_cn = "var lang_cn = {"
	for k, v := range result {
		row := make(map[string]interface{})
		row[v.Key_name] = v.Cn
		list_cn[k] = row

		if k == len(result)-1 {
			_str_cn += v.Key_name + ":\"" + v.Cn + "\""

			str_cn += v.Key_name + ":\"" + v.Cn + "\""
			str_en += v.Key_name + ":\""+ v.En + "\""
			str_th += v.Key_name + ":\"" + v.Th + "\""
		}else{
			_str_cn += v.Key_name + ":\"" + v.Cn + "\","

			str_cn += v.Key_name + ":\"" + v.Cn + "\","
			str_en += v.Key_name + ":\""+ v.En + "\","
			str_th += v.Key_name + ":\"" + v.Th + "\","
		}

	}
	str_cn +="}"
	str_en +="}"
	str_th +="}"
	_str_cn +="}"

	data :=  []byte(_str_cn)
	if ioutil.WriteFile(libs.CurrentPath() + "/static/cn.js",data,0644) == nil {
		fmt.Println("写入文件成功:","cn")
	}
	data =  []byte(str_cn)
	if ioutil.WriteFile(libs.CurrentPath() + "/static/cn1.js",data,0644) == nil {
		fmt.Println("写入文件成功:","cn1")
	}

	//file_cn, _ := os.Create("/Users/alex/Documents/go/src/adminapi/static/cn1.js")
	//enc_cn := json.NewEncoder(file_cn)
	//err_cn := enc_cn.Encode(str_cn)
	//if err_cn != nil {
	//	fmt.Println("错误:","cn_js")
	//}

	self.ajaxMsg("", MSG_OK)
}


func (self *KeywordController) TableAddrs() {

	redis := self.cache
	timeoutDuration := 10*60 * time.Second
	//if err = bm.Put("uid", "lkaslcmlaksmclkasmdc", timeoutDuration); err != nil {
	//	fmt.Print("set Error", err)
	//}
	//get := bm.Get("uid")
	//fmt.Print(string(get.([]byte)))
	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}

	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}
	self.pageSize = limit

	key := fmt.Sprintf("uid_data%d",page)
	get := redis.Get(key)

	if get != nil {
		//redislist := string(get.([]byte))
		//fmt.Print(redislist)
		//row := map[string]interface{}
		var row []models.KeyWord
		json.Unmarshal(get.([]byte),&row)
		list := make([]map[string]interface{}, len(row))
		for k, v := range row {
			row := make(map[string]interface{})
			row["id"] = v.Id
			row["key_name"] = v.Key_name
			row["cn"] = v.Cn
			row["en"] = v.En
			row["th"] = v.Th
			list[k] = row
		}
		redis_count := redis.Get("uid_count").([]byte)
		int64, _ := strconv.ParseInt(string(redis_count), 10, 64)
		self.ajaxList("成功", MSG_OK, int64, list)

	}

	//查询条件
	filters := make([]interface{}, 0)

	//filters = append(filters, "fle_city_code__exact", "TH0113")

	result,count := models.ParcelAddrGetList(page, self.pageSize, filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["key_name"] = v.Pno
		row["cn"] = v.Orig_addr
		row["en"] = v.Clean_addr
		row["th"] = v.Fle_city_code
		row["th001"] = 1111

		sum := 0
		for i := 0; i < 10000 ; i++  {
			sum = sum + i
		}
		row["th001"] = sum
		list[k] = row
	}
	b, _ := json.Marshal(list)
	if err = redis.Put(key, string(b), timeoutDuration); err != nil {
		fmt.Print("set Error", err)
	}
	if err = redis.Put("uid_count", count, timeoutDuration); err != nil {
		fmt.Print("set Error", err)
	}
	self.ajaxList("成功", MSG_OK, count, list)
}